<template>
  <d2-container>
    <template slot="header" class="query-area">
      <el-form ref="indexForm" :model="indexForm" label-width="100px" style="height:auto">
        <template>
          <el-row class="query-row">
            <el-col :span="5">
               <el-form-item label="类型" prop="categoryType">
                  <el-select v-model="indexForm.categoryType" placeholder="请选择" style="width: 100%;">
								    <el-option value="1" label="主食">主食</el-option>
								    <el-option value="2" label="加菜">加菜</el-option>
								    <el-option value="3" label="饮料/自选/餐盒/补差">饮料/自选/餐盒/补差</el-option>
                    <el-option value="4" label="套餐">套餐</el-option>
							    </el-select>
               </el-form-item>
            </el-col>
            <el-col :span="5">
               <el-form-item label="分类名称" prop="categoryName">
                  <el-input type="text" v-model="indexForm.categoryName" placeholder="请输入分类名称"></el-input>
               </el-form-item>
            </el-col>
            <el-col :span="5">
               <el-form-item label="分类编码" prop="categoryCode">
                  <el-input type="text" v-model="indexForm.categoryCode" placeholder="请输入分类编码"></el-input>
               </el-form-item>
            </el-col>
            <el-col :span="5">
               <el-form-item label="上级分类" prop="parentCategoryName">
                  <el-input type="text" v-model="indexForm.parentCategoryName" placeholder="请输入上级分类"></el-input>
               </el-form-item>
            </el-col>
            <el-col :span="10">
						<el-form-item label="创建时间" prop="time">
							<el-date-picker style="width:100%"
									v-model="time"
									type="datetimerange"
									:picker-options="pickerOptions"
									range-separator="至"
									start-placeholder="开始日期"
									end-placeholder="结束日期"
									value-format="timestamp"
									align="right"
									:default-time="['00:00:00', '23:59:59']"
								></el-date-picker>
						</el-form-item>
					  </el-col>
            <el-col :span="6">
               <el-form-item>
                  <el-button type="primary" size="medium" @click="submitForm('indexForm')">查询</el-button>
                  <el-button type="primary" plain size="medium" @click="resetForm('indexForm')">重置</el-button></el-form-item>
            </el-col>
          </el-row>
        </template>
      </el-form>
    </template>
    <template>
      <div>全部分类</div>
      <el-tree accordion :data="treeData" :props="treeProps" style="width: 15%; float: left;"></el-tree>
    </template>
   <template>
      <el-button v-if="shopId > 0" slot="header" type="primary" style="margin-bottom: 5px" @click="addChange">新 增</el-button>
      <el-table
          :data="tableData"
          stripe border
          row-key="id"
          style="width: 85%;"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="index"
            label="序号"
            width="50">
          </el-table-column>
          <el-table-column label="门店" prop="shopName" align="center" width="120"></el-table-column>
          <el-table-column
            prop="categoryType"
            label="类型">
            <template slot-scope="scope">
            <template v-if="scope.row.categoryType == 1">
							主食
						</template>
            <template v-if="scope.row.categoryType == 2">
							加菜
						</template>
            <template v-if="scope.row.categoryType == 3">
							饮料/自选/餐盒/补差
						</template>
            <template v-if="scope.row.categoryType == 4">
							套餐
						</template>
            </template>
          </el-table-column>
          <el-table-column
            prop="categoryName"
            label="分类名称">
          </el-table-column>
          <el-table-column
            prop="categoryCode"
            label="分类编码">
          </el-table-column>
          <el-table-column
            prop="parentCategoryName"
            label="上级分类">
          </el-table-column>
          <el-table-column
            prop="isEnable"
            label="是否启用"
            width="80">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.isEnable==0">否</el-tag>
              <el-tag v-if="scope.row.isEnable==1">是</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="remark"
            label="备注"
            width="100">
          </el-table-column>
          <el-table-column
            prop="createTime"
            width="100"
            label="创建时间" :formatter="forDateCreate">
          </el-table-column>
          <el-table-column
            prop="reviseTime"
            width="100"
            label="修改时间" :formatter="forDateRevise">
          </el-table-column>
          <el-table-column
            fixed="right"
            width="150"
            label="操作">
            <template slot-scope="scope">
              <el-button type="warning" size="small" @click="updateRow(scope.row.id)">编辑</el-button>
              <el-button
                @click.native.prevent="deleteRow(scope.row)"
                type="danger"
                size="small">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table> 
    </template>
    <!-- 页脚部分 -->
		<template slot="footer">
			<div class="page">
				<el-pagination
					background
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="currentPage"
					:page-sizes="[10, 20, 50, 100]"
					:page-size="pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="total"
				></el-pagination>
			</div>
		</template>
    <template>
      <div>
          <keep-alive>
              <addPage :addPage="addComponent" @on-addPage-change="onAddPageChange" @on-loadlist-change="fetchData" ></addPage>
          </keep-alive>
      </div>
      <div>
          <keep-alive>
              <updatePage :updatePage="updateComponent" @on-updatePage-change="onUpdatePageChange" @on-loadlist-change="fetchData" :uId="updateId" @on-id-change="onIdChange"></updatePage>
          </keep-alive>
      </div>
    </template>
  </d2-container>
</template>

<script>
import { findProductCategoryListByPage, findCategoryTree, del } from '@api/restaurant/merchant/productCategory'
import addPage from './add'
import updatePage from './update'
import dayjs from 'dayjs'
import { mapState } from 'vuex'
export default {
  name: 'category-index',
  components: {
    addPage,
    updatePage
  },
  data () {
    return {
      indexForm: {
        categoryType: '',
        categoryName: '',
        categoryCode: '',
        parentCategoryName: '',
        createTimeBegin: '',
        createTimeEnd: ''
      },
      time: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      treeData: [],
      treeProps: {
        label:function(data,node){
          return data.categoryName;
        },
      },
      tableData: [],
      currentPage: 1,
	  pageSize: 10,
	  total: 0,
	  multipleSelection: [],
      addComponent: false,
      updateComponent: false,
      updateId: ""
    }
  },
  mounted () {
    this.fetchData()
  },
  computed: {
	  ...mapState('d2admin/permission', ['shopId'])
  },
  methods: {
    /**双向绑定 start */
    addChange() {
     this.addComponent = !this.addComponent
    },
    onAddPageChange(val){
     this.addComponent=val;//④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
    },
    updateChange(){
      this.updateComponent=!this.updateComponent
    },
    onUpdatePageChange(val){
      this.updateComponent=val//④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
    },
    idChange(val){
      this.updateId = val;
    },
    onIdChange(val){
      this.updateId = val//④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
    },
    /**双向绑定 end */
    resetPage () {
        this.currentPage = 1,
        this.pageSize = 10,
        this.total = 0
    },
	submitForm (formName) {
		this.resetPage()
        this.fetchData()
	},
	resetForm (formName) {
		this.$refs[formName].resetFields()
        this.time = []
        this.resetPage()
        this.fetchData()
	},
    fetchData () {
      this.loading = true
      findCategoryTree({

      }).then(res => {
        this.treeData = res.data;
        this.loading = false
      }).catch(err => {
        console.log('err', err)
        this.loading = false
      })
      
      this.loading = true
      this.indexForm.createTimeBegin = this.time[0] == null ? '' : dayjs(this.time[0]).format('YYYY-MM-DD HH:mm:ss')
      this.indexForm.createTimeEnd = this.time[1] == null ? '' : dayjs(this.time[1]).format('YYYY-MM-DD HH:mm:ss')
      findProductCategoryListByPage({
        categoryType: this.indexForm.categoryType,
        categoryName: this.indexForm.categoryName,
        categoryCode: this.indexForm.categoryCode,
        parentCategoryName: this.indexForm.parentCategoryName,
        startTime: this.indexForm.createTimeBegin,
        endTime: this.indexForm.createTimeEnd,
        currentPage: this.currentPage,
        pageSize: this.pageSize
      }).then(res => {
        this.tableData = res.data.content
        this.total = res.data.total
        this.loading = false
      }).catch(err => {
        console.log('err', err)
        this.loading = false
      })
    },
    handleSizeChange (val) {
	    this.pageSize = val
		this.fetchData()
	},
	handleCurrentChange (val) {
	    this.currentPage = val
		this.fetchData()
	},
	handleSelectionChange (val) {
        this.multipleSelection = val
    },
    deleteRow(row) {
      this.$confirm("确认删除" + row.categoryName + "？").then(_ => {
        this.loading = true
        del({
          id:row.id
        })
          .then(res => {
            if (res.code == '000000') {
              this.$message({ message: res.message, type: "success" });
              this.fetchData();
              this.loading = false
            } else {
              this.$message({message: res.message, type:'error'});
              return;
            }
          })
          .catch(err => {
            console.log("err", err);
            this.loading = false;
          });
      });
    },
    updateRow(id){
      this.updateChange()
      this.idChange(id)
    },
    forDateCreate(row, column){
      return row.createTime==null?"":dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
    },
    forDateRevise(row, column){
      return row.reviseTime==null?"":dayjs(row.reviseTime).format('YYYY-MM-DD HH:mm:ss')
    }
  }
}
</script>
